package com.blb.edusearchservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.blb.common.entity.Course;
import com.blb.common.entity.PageEntity;
import com.blb.common.entity.ResponseResult;
import com.blb.edusearchservice.client.CourseServiceClient;
import com.blb.edusearchservice.dao.ElasticsearchDAO;
import com.blb.edusearchservice.entity.ElasticsearchEntity;
import com.blb.edusearchservice.service.CourseIndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CourseIndexServiceImpl implements CourseIndexService {

    public static final String INDEX_NAME = "course";

    @Resource
    private ElasticsearchDAO dao;

    @Resource
    private CourseServiceClient courseServiceClient;

    /**
     * 初始化课程索引
     */
    @Override
    public void initCourseIndex() {
        //如果存在课程索引先删除
        try {
            if(dao.exists(INDEX_NAME)){
                dao.delete(INDEX_NAME);
            }
            //再创建课程索引
            dao.create(INDEX_NAME);
            //调用课程服务获得课程列表
            ResponseResult<List<Course>> courses = courseServiceClient.getAllCourses();
            //将数据包装到ES实体类集合中
            List<ElasticsearchEntity> entities = new ArrayList<>();
            courses.getData().forEach(course -> {
                entities.add(new ElasticsearchEntity(String.valueOf(course.getId()),course));
            });
            //批量插入ES
            dao.insertBatch(INDEX_NAME,entities);
            log.info("批量导入课程成功 {}",entities);
        } catch (IOException e) {
            log.error("批量导入出错",e);
        }
    }

    @Override
    public PageEntity<Course> searchCourse(Map<String, String> map) {
        int current = 0;
        if(map.containsKey("current")){
            current = Integer.parseInt(map.get("current"));
        }
        int size = 10;
        if(map.containsKey("size")){
            size = Integer.parseInt(map.get("size"));
        }
        Map<String,String> search = null;
        if(map.containsKey("search")){
            search = JSON.parseObject(map.get("search"), Map.class);
        }
        Map<String,String> sort = null;
        if(map.containsKey("sort")){
            sort = JSON.parseObject(map.get("sort"),Map.class);
        }
        try {
            PageEntity pageEntity = dao.search(INDEX_NAME, search, sort, current, size, Course.class,"courseName","brief");
            return pageEntity;
        } catch (Exception e) {
            log.error("搜索出错",e);
        }
        return null;
    }
}
